package com.dagene.weixin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dagene.weixin.entity.Newstable;
import com.dagene.weixin.repository.NewtableDao;

@Component
@Transactional(rollbackFor = Exception.class)
public class NewstableService {
	@Autowired
	NewtableDao newtableDao;

	public Newstable save(Newstable article) {
		return newtableDao.save(article);
	}

	public Page<Newstable> getNewsByPage(short type, Pageable page) {
		return newtableDao.findByType(type, page);
	}

	public List<Newstable> getNewsByType(short type) {
		return newtableDao.findByType(type);
	}

	public Newstable getNewsById(int id) {
		return newtableDao.findOne(id);
	}

	public void deleteNews(int id) {
		newtableDao.delete(id);
	}

	public List<Newstable> queryNews(String title, String type) {
		if (StringUtils.isEmpty(title) && StringUtils.isEmpty(type)) {
			return (List<Newstable>) newtableDao.findAll();
		} else if (StringUtils.isEmpty(title) && !StringUtils.isEmpty(type)) {
			return newtableDao.findByType(Short.parseShort(type));
		} else if (!StringUtils.isEmpty(title) && StringUtils.isEmpty(type)) {
			return newtableDao.findByTitle(title);
		} else {
			return newtableDao.findByTitleAndType(title, Short.parseShort(type));
		}
	}
}
